package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {
    @Resource
    private IUserService userService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private IFollowService followService;

    @Override
    public Blog queryBlogById(Long id) {
        // 1. 根据id 去查blog
        Blog blog = getById(id);
        if (blog == null) {
            throw new RuntimeException("点评不存在");
        }
        // 填充帖子发起者的信息
        this.queryBlogUser(blog);
        // 判断当前用户是否对这个帖子点赞
        this.currentUserLikedOrNot(blog);
        // 3. 返回
        return blog;
    }

    private void currentUserLikedOrNot(Blog blog) {
        Long id = blog.getId();
        // 1. 根据id拼接出key
        String blogKey = RedisConstants.BLOG_LIKED_KEY + id;
        // 2. 通过ThreadLocal拿到当前用户的id
        UserDTO user = UserHolder.getUser();
        if (user == null) {
            return ;
        }
        // 3. 看下zset里面有没有这个用户的id
        Double score = stringRedisTemplate.opsForZSet().score(blogKey, user.getId().toString());
        blog.setIsLike(score != null);
    }

    @Override
    public List<Blog> queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = this.query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog ->{
            this.queryBlogUser(blog);
            currentUserLikedOrNot(blog);
        });
        return records;
    }

    @Override
    public void likeBlog(Long id) {
        // 1. 获取当前用户
        UserDTO user = UserHolder.getUser();
        if (user == null) {
            throw new RuntimeException("请先登录");
        }
        // 2. 去sortedSet里面看下有没有这个用户的id
        String blogKey = RedisConstants.BLOG_LIKED_KEY + id;
        Double score = stringRedisTemplate.opsForZSet().score(blogKey, user.getId().toString());
        if (score != null) {
            // 3. 有，取消点赞
            // 3.1 数据库 like = like - 1
            LambdaUpdateWrapper<Blog> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.setSql("liked = liked - 1");
            updateWrapper.eq(Blog::getId, id);
            boolean isSuccess = update(updateWrapper);
            if (isSuccess) {
                // 3.2 ZREM key member
                stringRedisTemplate.opsForZSet().remove(blogKey, user.getId().toString());
            }
        } else {
            // 4. 没有点赞
            // 4.1 数据库 like = like + 1
            LambdaUpdateWrapper<Blog> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.setSql("liked = liked + 1");
            updateWrapper.eq(Blog::getId, id);
            boolean isSuccess = update(updateWrapper);
            if (isSuccess) {
                // 4.2 ZADD key score member
                stringRedisTemplate.opsForZSet().add(blogKey, user.getId().toString(), System.currentTimeMillis());
            }
        }
    }

    @Override
    public List<UserDTO> queryLikes(Long id) {
        String blogKey = RedisConstants.BLOG_LIKED_KEY + id;
        // 1. 查询点赞的前5名
        Set<String> top5 = stringRedisTemplate.opsForZSet().range(blogKey, 0, 4);
        if (CollectionUtils.isEmpty(top5)) {
            return Collections.emptyList();
        }
        // 2. 解析出id
        List<Long> ids = top5.stream()
                .map(Long::valueOf)
                .collect(Collectors.toList());
        String idStr = StrUtil.join(",", ids);
        // 3. 根据ids查用户
        List<UserDTO> userDTOS = userService.query()
                .in("id", ids).last("order by field(id, " + idStr + ")").list()
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        // 4. 返回
        return userDTOS;
    }

    @Override
    public void saveBlog(Blog blog) {
        // 1. 获取当前用户
        UserDTO user = UserHolder.getUser();
        if (user == null) {
            throw new RuntimeException("请登录");
        }
        Long userId = user.getId();
        // 2. 给blog的userId填上去
        blog.setUserId(userId);
        // 3. 保存到数据库
        boolean isSuccess = save(blog);
        if (!isSuccess) {
            throw new RuntimeException("添加点评失败");
        }
        // 4. 保存成功，根据userId，去数据库查出是那些用户关注了该用户
        List<Follow> followList = followService.lambdaQuery().eq(Follow::getFollowUserId, userId).list();
        // 5. 将blog的id + 时间搓推到这个关注用户的邮件箱上
        followList.forEach(follow -> {
            Long followUserId = follow.getUserId();
            stringRedisTemplate.opsForZSet().add(RedisConstants.FEED_KEY + followUserId
                    , blog.getId().toString(), System.currentTimeMillis());
        });
    }

    @Override
    public ScrollResult queryBlogOfFollow(Long max, Integer offset) {
        ScrollResult scrollResult = new ScrollResult();
        // 1. 获取当前的userId
        UserDTO user = UserHolder.getUser();
        if (user == null) {
            throw new RuntimeException("请登录");
        }
        Long userId = user.getId();
        // 2. 根据提供的max和offset去当前用户的收件箱里面
        final int count = 2;
        final double min = 0d;
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet()
                .reverseRangeByScoreWithScores(
                RedisConstants.FEED_KEY + userId,
                min, max, offset, count
        );
        if (CollectionUtils.isEmpty(typedTuples)) {
            scrollResult.setList(Collections.emptyList());
            return scrollResult;
        }
        // 3. 获取下一次查询的max和offset，也就是当前的min和min相同的个数
        long nextMax = System.currentTimeMillis();
        int nextOffset = 1;
        List<String> blogIdsStrList = new ArrayList<>(count);
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
            Double blogPostTime = typedTuple.getScore();
            String blogId = typedTuple.getValue();
            blogIdsStrList.add(blogId);
            if (blogPostTime == nextMax) {
                nextOffset++;
            } else {
                nextMax = blogPostTime.longValue();
                nextOffset = 1;
            }
        }
        // 4. ids --> Blogs 注意blogs要有序
        List<Long> blogIds = blogIdsStrList.stream().map(Long::valueOf).collect(Collectors.toList());
        String idStr = StrUtil.join(",", blogIds);
        // 3. 根据ids查用户
        List<Blog> blogList = query()
                .in("id", blogIds).last("order by field(id, " + idStr + ")").list()
                .stream()
                .peek(blog -> {
                    // 5. 检查当前用户是否点赞和查询blogs中的所有user信息
                    this.queryBlogUser(blog);
                    this.currentUserLikedOrNot(blog);
                })
                .collect(Collectors.toList());
        // 6. 用blogs和nextMax和nextOffset组装成ScrollResult
        scrollResult.setOffset(nextOffset);
        scrollResult.setMinTime(nextMax);
        scrollResult.setList(blogList);
        // 7. 返回
        return scrollResult;
    }

    private void queryBlogUser(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }
}
